﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;
using System.Data;
using WoSoft.PACS.Utility;

namespace WoSoft.PACS.Data.DBProvider
{
    /// <summary>
    /// Oracle帮助类
    /// </summary>
    public class ODBCHelper : IDisposable
    {
        //private const string CONSTR = @"Data Source={0}/{1};Persist Security Info=True;User ID={2};Password={3}";
        private const string CONSTR = @"Dsn={0};Uid={1};Pwd={2}";

        private OdbcConnection _connection;

        /// <summary>
        /// 初始连接对象
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="instance"></param>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        public ODBCHelper(string ip, string instance, string name, string pwd)
        {
            //var con = string.Format(CONSTR, ip, instance, name, pwd);
            var con = string.Format(instance, name, pwd);
            _connection = new OdbcConnection(con);
        }

        /// <summary>
        /// 执行SQL查询
        /// </summary>
        /// <param name="sqlText">SQL脚本</param>
        /// <returns>返回结果表</returns>
        public DataTable QueryText(string sqlText, params OdbcParameter[] commandParameters)
        {
            try
            {
                if (_connection.State != ConnectionState.Open)
                {
                    _connection.Open();
                }
                var ds = new DataSet();
                OdbcCommand cmd = new OdbcCommand(sqlText, _connection);
                cmd.CommandType = CommandType.Text;
                if (commandParameters != null)
                {
                    cmd.Parameters.AddRange(commandParameters);
                }

                using (OdbcDataAdapter da = new OdbcDataAdapter(cmd))
                {
                    da.Fill(ds);
                }

                if (ds != null && ds.Tables.Count > 0)
                {
                    return ds.Tables[0];
                }

                return null;
            }
            catch (Exception ex)
            {
                LogHelper.Error("数据库执行脚本异常", ex);
                return null;
            }
        }

        /// <summary>
        /// 释放对象
        /// </summary>
        public void Dispose()
        {
            if (_connection != null)
            {
                if (_connection.State == System.Data.ConnectionState.Open)
                {
                    _connection.Close();
                }
            }
        }
    }
}
